<?php

namespace Sharks\Core\Persistence\QueryBuilder;

use ReflectionClass;
use Sharks\Core\Exception\DatabaseException;
use Sharks\Core\Persistence\Model;

/**
 * 抽象类
 */
class AbstractQuery {

    protected $class;

    /**
     * 处理查询返回时是否将对象装入类
     * @param $class
     */
    public function map($class) {
        if (is_string($class) && class_exists($class)) {
            $class = new ReflectionClass($class);
        }

        if (!is_a($class, ReflectionClass::class) || !$class->isSubclassOf(Model::class)) {
            throw new DatabaseException("$class 不是Model的子类");
        }
        $this->class = $class;
    }


    /**
     * 检查是否有错误
     * @throws DatabaseException
     */
    protected function checkError($stmt) {
        if ('00000' !== $stmt->errorCode()) {
            $errorCode = $stmt->errorCode();
            $errorInfo = $stmt->errorInfo();
            throw new DatabaseException("数据库查询错误，SQLSTATE error code: $errorCode, Driver error code: $errorInfo, Driver error message: $error[2], last query: $last_query");
        }
    }
}